import asyncio
import time

from sanic import Sanic
from sanic.response import HTTPResponse, text, json,file,html
from sanic.views import HTTPMethodView

import websockets

# sanic server.app
app = Sanic("myapp")
#加载静态文件
# app.static("/", "./web")
app.static("/", "./AIimg")
# app.static("/img", "./AIcut")

from check import CHECKER
from controller import CONTROLLER
from Config.Config import DBConfig

from dopoai_server import AISERVER

@app.route('/')
async def hello(request):
    print('hello')
    return text('hello')

@app.route('/check')
async def check(request):
    num = request.args.get("num")
    if num == None:
        num = 10
    print('本次执行%s次',num)
    check_donor = CHECKER()
    trxt = await check_donor.checkDonor(num)

    # app.add_task(check_donor.checkDonor(num))
    return text('succ')

@app.route('/checkAgain')
async def checkAgain(request):
    num = request.args.get("num")
    if num == None:
        num = 1
    print('本次执行%s次', num)
    check_donor = CHECKER()
    await check_donor.checkDonorAgain(num)
    # app.add_task(check_donor.checkDonorAgain(num))
    return text('over')
@app.route('/checkSysError')
async def checkSysError(request):
    num = request.args.get("num")
    if num == None:
        num = 1
    print('本次执行%s次', num)
    check_donor = CHECKER()
    await check_donor.checkDonorSysError(num)
    # app.add_task(check_donor.checkDonorAgain(num))
    return text('over')
# app登录
@app.get("/login")
async def appLogin(request):
    username = request.args.get('username')
    password = request.args.get('password')
    code = 0
    data = []
    # close_db(db, cursor)
    data = {
                "id": '1',
                "username": "username",
                "area": "area",
                "name": "name",
                "town": "town"
            }

    return json({
        "code": code,
        "data": data
    })

@app.get('/get_nat_list')
async def get_nat_list(request):
    page = request.args.get('page')
    if page == None:
        page = 1
    pageSize = 10

    con = CONTROLLER()
    donors = con.get_nat_list(num =0,page = 1,pageSize = 10)

    code = 1
    return json({
        "code": code,
        "data": donors,
        "page": 1,
        "count": len(donors)
    })

@app.get('/get_setting')
async def get_setting(request):
    code = 1
    table = app.config.STATION
    return json({
        "code": code,
        "data": table
    })

@app.post('/set_setting')
async def set_setting(request):
    settings = request.json['setting']
    code = 1
    app.config.STATION = settings['nat']['station_code']
    return json({
        "code": code
    })

@app.get('/get_count')
async def get_count(request):
    code = 1
    con = CONTROLLER()
    donors = con.get_count(num =0);
    return json({
        "code": code,
        "data": donors,
        "page": 1,
        "count": len(donors)
    })
@app.get('/export_excel')
async def export_excel(request):
    code = 1
    con = CONTROLLER()
    path = con.export_excel(num =0);
    return json({
                "code": 1,
                "url": './export_download?name=table.xlsx&path=' + path
            })

# 统一文件下载
@app.get("/export_download")
async def handler_download(request):
    return await file(request.args.get('path'), filename=request.args.get('name'))





@app.route('/checkWebsocket')
async def websocket(request):
    db = DBConfig.db
    cursor = db.cursor()
    # 排除拒用的 未轮询的记录
    sql = f'select * from  {app.config.STATION}  where is_checked  = 0 and donor_status != "YJ"  limit 1000'
    cursor.execute(sql)
    donors = cursor.fetchall()

    for donor in donors:
        time.sleep(5)
        await sendMessage(donor['donor_name'])
    return text('hello')


async def sendMessage(msg):
    async with websockets.connect('ws://127.0.0.1:5678') as websocket:
        await websocket.send(msg)



@app.route('/ai')
async def ai(request):
    num = request.args.get("num")
    if num == None:
        num = 1
    # print('本次执行%s次', num)
    check_donor = AISERVER()
    yzm = check_donor.deelPic(num)
    # app.add_task(check_donor.checkDonorAgain(num))
    text = f"<img src = 'orign.jpg'><br><img src = '1.jpg'><br>" \
           f"<img src = 'AIimg_cut/1.jpg'><br><img src = 'AIimg_cut/2.jpg'><br>" \
           f"<img src = 'AIimg_cut/3.jpg'><br><img src = 'AIimg_cut/4.jpg'><br>{yzm}"
    return  html(text)


if __name__ == "__main__":
    # app.run(host='0.0.0.0', port=8000, debug=True, auto_reload=True, access_log=False, workers=4)
    # app.run(host='0.0.0.0', port=8000, debug=False, fast=True)
    app.run(host='0.0.0.0', port=9000, debug=False)




